import wx from 'weixin-js-sdk';
import {
  setToken,
} from '@/utils/auth';
import {
  getWechatCode,
  getWechatOpenId,
  getWxCodeConfig,
} from '../api/wechart.js';
import {
  customLogin,
} from '../api/login';

import {
  getUrlParam,
  isLocal,
} from './common.js';

export const beforeCreate = async ({ store }, callback) => {
  await getWxUser(store);
  //#ifdef H5
  await initWx(callback);
  //#endif
  // callback()
};

export const getWxUser = async (store) => {
  const urlParam = getUrlParam();
  const openId = uni.getStorageSync('openId');
  if (openId) {
    const res = await customLogin({
      openId,
    }).catch(() => {
    });
    if (res && res.code === 200) {
      setToken(res.token);
      store.dispatch('LoginSuccess', {
        token: res.token,
        state: res.state,
      });
      return;
    }
  }
  // if (location.origin.includes('test')) {
  //   urlParam.code = 'test';
  // }
  if (urlParam.code) {
    const res = await getWechatOpenId({
      code: urlParam.code,
    });
    // if (location.origin.includes('test')) {
    //   res.openid = 'test';
    // }
    if (res.openid) {
      uni.setStorageSync('openId', res.openid);
      let url = `${location.origin}${location.pathname}${location.hash}`;
      url += `${location.hash.includes('?') ? '&' : '?'}unCheckToken=1`;
      location.replace(url);
    }
    console.log(res);
  }
};

export const initWx = async (callback) => {
  const url = location.href.split('#/')[ 0 ];
  const res = await getWxCodeConfig({
    url,
  });
  if (res.code === 200) {
    const {
      data,
    } = res;
    wx.config({
      debug: isLocal, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
      appId: data.appId, // 必填，公众号的唯一标识
      timestamp: data.timestamp, // 必填，生成签名的时间戳
      nonceStr: data.nonceStr, // 必填，生成签名的随机串
      signature: data.signature, // 必填，签名
      jsApiList: [ 'scanCode', 'scanQRCode' ], // 必填，需要使用的JS接口列表
    });
    wx.ready(() => {
      callback();
    });
  }
};

export default {
  beforeCreate,
  initWx,
};
